package com.ychen.goodscenter.service.impl;

import com.ychen.goodscenter.dao.OrderInfoMapper;
import com.ychen.goodscenter.entity.OrderInfo;
import com.ychen.goodscenter.enums.OrderStatusEnum;
import com.ychen.goodscenter.service.OrderService;
import com.ychen.goodscenter.service.biz.OrderBizService;
import com.ychen.goodscenter.vo.req.SubmitOrderReq;
import com.ychen.usercenter.api.AccountFacade;
import com.ychen.usercenter.vo.PayForOrderReq;
import com.ychen.usercenter.vo.PayForOrderResp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private AccountFacade accountFacade;

    @Autowired
    private OrderBizService orderBizService;

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Override
    public OrderInfo submitOrder(SubmitOrderReq req) {
        //库存足够就扣减库存，并创建订单（事务）
        OrderInfo orderInfo = orderBizService.reduceStockAndCreateOrder(req);

        //向用户中心发起支付请求
        PayForOrderReq payForOrderReq = buildPayForOrderReq(orderInfo);
        PayForOrderResp resp = accountFacade.payForOrder(payForOrderReq);

        if (!resp.getIsSuccess()) {
            // 支付失败
            orderBizService.rollbackStockAndUpdateOrder(orderInfo);
        } else {
            // 支付成功
            orderInfo.setOrderStatus(OrderStatusEnum.PAID.getCode());
            orderInfoMapper.updateOrderStatusByPrimaryKey(orderInfo.getId(), orderInfo.getOrderStatus());
        }
        return orderInfo;
    }


    private PayForOrderReq buildPayForOrderReq(OrderInfo orderInfo) {
        PayForOrderReq req = new PayForOrderReq();
        req.setOrderId(orderInfo.getId());
        req.setSrcAccountId(orderInfo.getBuyerId());
        req.setTargetAccountId(orderInfo.getSellerId());
        req.setTransferAmount(orderInfo.getOrderAmount());
        return req;
    }
}
